<template>
  <BaseModal :show="modalActive" @close="closeAttachmentUploadModal">
    <template #header>
      <div class="flex justify-between w-full">
        {{ modalStore.title }}
        <BaseIcon
          name="XMarkIcon"
          class="w-6 h-6 text-gray-500 cursor-pointer"
          @click="closeAttachmentUploadModal"
        />
      </div>
    </template>

    <form action="">
      <div class="px-4 pt-6 sm:px-6 sm:pt-6 text-sm text-gray-500">{{ $t('attachment.tip') }}</div>

      <div class="px-4 pb-4 sm:px-6 sm:pb-6">
        <BaseInputGroup>
          <BaseFileUploader
            @change="onFileInputChange"
            accept="image/*"
          />
        </BaseInputGroup>
      </div>

      <div
        class="z-0 flex justify-end p-4 border-t border-gray-200 border-solid"
      >
        <BaseButton
          variant="gray"
          class="mr-3"
          type="button"
          @click="closeAttachmentUploadModal"
        >
          {{ $t('general.cancel') }}
        </BaseButton>


      </div>
    </form>
  </BaseModal>
</template>

<script setup>
import { ref, computed } from 'vue'
// pinia
import { useModalStore } from '@/stores/components/modal'
import { useAttachmentStore } from '@/stores/attachment'
// 

const modalStore = useModalStore()
const attachmentStore = useAttachmentStore()

const isSaving = ref(false)

const modalActive = computed(() => {
  return modalStore.active && modalStore.componentName === 'AttachmentUploadModal'
})

//const subErr = ref('[VATTT], dept name no exist!')

function closeAttachmentUploadModal() {
  modalStore.closeModal()
}

let FileBlob = ref(null)

async function onFileInputChange(fileName, file, fileCount, fileList) {
  console.log('文件变更11', fileCount, fileList, fileName)

  FileBlob.value = file

  if (FileBlob.value) {
    let formData = new FormData()

    formData.append(
      'file',
      FileBlob.value,
      fileName
    )

    await attachmentStore.addItem(formData)

    if (modalStore.refreshData) {
      modalStore.refreshData()
    }
    
    isSaving.value = false
    closeAttachmentUploadModal()
  }
}

</script>
